package com.qmyx.supplychain.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.enums.ExpressEnums;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.PropertiesReader;
import com.kuaidi100.sdk.utils.SignUtils;
import com.ytjj.qmyx.supplychain.common.constants.RedisConstants;
import com.ytjj.qmyx.supplychain.common.enums.NeedPhoneExpressEnum;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.ReissueLogisticsMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxReissueLogistics;
import com.ytjj.qmyx.supplychain.service.ExpressOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 补单物流定时任务
 * @author EDY
 */
@Component
@Slf4j
public class ReissueLogisticsTask {

    /**
     * 快递更新时间差值 30分钟
     */
    private static final long DIFFERENCE_VALUE = 1800L;

    @Resource
    private ReissueLogisticsMapper reissueLogisticsMapper;
    @Resource
    private ExpressOrderService expressOrderService;
    @Resource
    private RedisService redisService;

    /**
     * 40分钟执行一次
     * 补充已上传补单物流快递单号的补单记录的快递信息
     */
    @Scheduled(cron = "0 0/40 * * * ?")
    public void repairPrepaidOrders(){
        try{
            log.info("===== 开始查询补单物流快递信息=====");
            List<YxReissueLogistics> reissueLogistics = reissueLogisticsMapper.queryReissueLogisticsList(90);
            if (!CollectionUtils.isEmpty(reissueLogistics)) {
                for (YxReissueLogistics logistic : reissueLogistics) {
                    QueryTrackResp resp = expressOrderService.getExpressInfoByReplacementOrder(logistic.getExpressNo(), logistic.getExpressCompanyNo(), logistic.getUserPhone());
                    if(null != resp){
                        YxReissueLogistics yxReissueLogistics = new YxReissueLogistics();
                        yxReissueLogistics.setId(logistic.getId());
                        if ("200".equals(resp.getStatus())) {
                            Date latestFDate = DateUtil.StrToTime(resp.getData().get(0).getFtime());
                            yxReissueLogistics.setLogisticsReceiptTime(latestFDate);
                            yxReissueLogistics.setExpressRecord(JSONObject.toJSONString(resp.getData()));
                            yxReissueLogistics.setExpressText(JSONObject.toJSONString(resp));
                            yxReissueLogistics.setStatusCode(Integer.valueOf(resp.getState()));
                            yxReissueLogistics.setStatusDesc(ExpressEnums.getStatusName(resp.getState()));
                            //快递签收
                            if ((ExpressEnums.isCheck(resp.getState()))) {
                                QueryTrackData queryTrackData = resp.getData().get(0);
                                Date checkDate = Optional.ofNullable(DateUtil.StrToTime(queryTrackData.getFtime())).orElse(new Date());
                                yxReissueLogistics.setCheckTime(checkDate);
                                reissueLogisticsMapper.updateReissueLogisticsFished(yxReissueLogistics);
                                //快递状态异常
                            }   else if (StringUtils.isNotEmpty(ExpressEnums.getExceptionName(resp.getState()))) {
                                //超时未更新
                                if(ExpressEnums.TIMED_OUT_NOT_UPDATED.getStatus().equals(resp.getState())){
                                    if (expressOrderService.isDelivery(resp.getData().get(0).getContext())) {
                                        //文字匹配，将第三方的默认超时状态，修改成适用于我们的超时未签收
                                        yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.OVERTIME_NOT_SIGNED_FOR.getStatus()));
                                        yxReissueLogistics.setStatusDesc(ExpressEnums.OVERTIME_NOT_SIGNED_FOR.getStatusName());
                                    } else {
                                        boolean caseOne = expressOrderService.isBetween(48L, 72L, latestFDate);
                                        boolean caseTwo = expressOrderService.isBetween(72L, null, latestFDate);
                                        if (caseOne || caseTwo) {
                                            String  desc = caseOne ? "物流超48小时未更新" : caseTwo ? "物流超72小时未更新" : "物流超时未更新";
                                            yxReissueLogistics.setStatusDesc(desc);
                                        }
                                    }
                                }
                                reissueLogisticsMapper.updateReissueLogisticsExpress(yxReissueLogistics);
                            //其他状态
                            } else {
                                //揽收
                                if (StringUtils.isNotEmpty(ExpressEnums.getCollectByStatus(resp.getState()))) {
                                    //如果是揽收中的已下单状态，需要特殊处理，因为快递100会返回物流文案："2023-10-13 14:17:46 已下单【该信息由快递100提供】"
                                    if(ExpressEnums.ORDERED.getStatus().equals((resp.getState()))){
                                        if(expressOrderService.isTimeOut(latestFDate,24)) {
                                            yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.NO_EXPRESS_DETAIL.getStatus()));
                                            yxReissueLogistics.setStatusDesc(ExpressEnums.NO_EXPRESS_DETAIL.getStatusName());
                                        }
                                    }else if (ExpressEnums.PENDING_COLLECTION.getStatus().equals((resp.getState()))) {
                                        if(expressOrderService.isTimeOut(latestFDate,24)){
                                            yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.TIMEOUT_PENDING_COLLECTION.getStatus()));
                                            yxReissueLogistics.setStatusDesc(ExpressEnums.TIMEOUT_PENDING_COLLECTION.getStatusName());
                                        }
                                    }else {
                                        if(expressOrderService.isTimeOut(latestFDate,24)) {
                                            yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.TIMED_OUT_NOT_UPDATED.getStatus()));
                                            yxReissueLogistics.setStatusDesc(ExpressEnums.TIMED_OUT_NOT_UPDATED.getStatusName());
                                        }

                                    }

//                                    if(expressOrderService.isTimeOut(latestFDate,24)) {
//                                        yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.TIMED_OUT_NOT_UPDATED.getStatus()));
//                                        yxReissueLogistics.setStatusDesc("揽收状态已超过24小时");
//                                    }
                                    reissueLogisticsMapper.updateReissueLogisticsExpress(yxReissueLogistics);
                                    //无状态
                                } else if (StringUtils.isEmpty(resp.getState())) {
                                    yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.NO_EXPRESS_STATUS.getStatus()));
                                    yxReissueLogistics.setStatusDesc(ExpressEnums.NO_EXPRESS_STATUS.getStatusName());
                                    reissueLogisticsMapper.updateReissueLogisticsExpress(yxReissueLogistics);
                                }  else {
                                    boolean caseOne = expressOrderService.isBetween(48L, 72L, latestFDate);
                                    boolean caseTwo = expressOrderService.isBetween(72L, null, latestFDate);
                                    //在途 的物流是否超48或72小时
                                    if (StringUtils.isNotEmpty(ExpressEnums.getAllInTransit(resp.getState())) && (caseOne || caseTwo)) {
                                        String desc = caseOne ? "物流超48小时未更新" : caseTwo ? "物流超72小时未更新" : "物流超时未更新";
                                        //是否已送达
                                        if (expressOrderService.isDelivery(resp.getData().get(0).getContext())) {
                                            //已送达，但第三方的状态是正常状态，需要修改成适用于我们的超时未签收
                                            yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.OVERTIME_NOT_SIGNED_FOR.getStatus()));
                                            yxReissueLogistics.setStatusDesc(ExpressEnums.OVERTIME_NOT_SIGNED_FOR.getStatusName());
                                        } else {
                                            yxReissueLogistics.setStatusCode(Integer.valueOf(ExpressEnums.TIMED_OUT_NOT_UPDATED.getStatus()));
                                            yxReissueLogistics.setStatusDesc(desc);
                                        }
                                    }
                                    reissueLogisticsMapper.updateReissueLogisticsExpress(yxReissueLogistics);

                                }
                            }
                        }else {
                            log.info("查询物流失败补单id：{}",logistic.getId());
                            Date supplementaryDay = logistic.getSupplementaryDay();
                            String statusDesc ="";
                            if (supplementaryDay != null) {
                                long value = System.currentTimeMillis() - supplementaryDay.getTime();
                                long valueHour = value / 1000 / 3600;
                                if (valueHour >= 24 && valueHour < 48) {
                                    statusDesc = "超24小时查无物流";
                                } else if (valueHour >= 48 && valueHour < 72) {
                                    statusDesc = "超48小时查无物流";
                                } else if (valueHour >= 72) {
                                    statusDesc = "超72小时查无物流";
                                }
                            }
                            logistic.setStatusDesc(statusDesc);
                            logistic.setStatusCode(-2);
                            reissueLogisticsMapper.updateReissueLogisticsExpress(logistic);
                        }
                    }
                }
            }
        }catch (Exception e) {
            log.error("===更新补单物流快递错误==={}",e);
        }

    }
}
